class UserController < ApplicationController
  before_filter :require_user, :except => [ :login, :logout, :create_admin_account ]

  def home
    @new_items = current_user.find_unseen_unpaid_bills
    
    @new_items.each do |item|
      item.seen = true
      item.save
    end
  end

  def login
    if request.post?
      user = User.authenticate(params[:user][:username], params[:user][:password])
      
      if user
        flash[:message] = 'Successfully logged in.'
        session[:current_user] = user.id
        redirect_home
      else
        flash[:error] = 'Invalid login details.'
      end
    end
  end
  
  def logout
    session[:current_user] = nil
    @current_user = nil
    flash[:message] = 'Successfully logged out.'
    redirect_to :action => 'login'
  end
  
  def profile
    @user = current_user
  
    if request.post?
      @user.update_attributes(params[:user])
      
      if @user.save
        flash[:message] = 'Profile updated.'
        redirect_home
      end
    end
  end
  
  def create_admin_account
    if User.count == 0
      if request.post?
        @user = User.new(params[:user])
        @user.role = 'admin'
        
        if @user.save
          flash[:message] = 'Administrator account created.'
          redirect_to :action => 'login'
        end
      end
    else
      redirect_home
    end
  end
end
